package com.rivues.util.realm;

import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.AllowAllCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rivues.core.RivuDataContext;
import com.rivues.module.platform.web.interceptor.LogIntercreptorHandler;
import com.rivues.module.platform.web.model.User;
import com.rivues.util.RivuTools;
import com.rivues.util.iface.authz.R3InnerUserAuthzImpl;
import com.rivues.util.iface.authz.UserAuthzFactory;
import com.rivues.util.realm.TrustedSSOAuthenticationToken;

public class R3ShiroRealm extends AuthorizingRealm {
	private final Logger log = LoggerFactory.getLogger(R3ShiroRealm.class); 
	public R3ShiroRealm(){
        // 设置无需凭证，因为从sso认证后才会有用户名
		setCredentialsMatcher(new AllowAllCredentialsMatcher());
		// 设置token为我们自定义的
		setAuthenticationTokenClass(TrustedSSOAuthenticationToken.class);
	}

	@Override
	/**

	 * 认证回调函数,登录时调用.

	 */
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken authcToken) {
		TrustedSSOAuthenticationToken token = (TrustedSSOAuthenticationToken) authcToken;
		User user = this.getUser(token.getUsername(), token.getPassword(),
				token.getOrgi());
		AuthenticationInfo info =  null ;
		if(user!=null){
			SecurityUtils.getSubject().getSession().setAttribute(RivuDataContext.USER_SESSION_NAME, user);
			info =  new SimpleAuthenticationInfo(user.getUsername(),
					user.getPassword(), getName()) ;
			clearCache(info.getPrincipals());
		}
		

 		return user != null ? info : null;

	}

	/**
	 * 获得授权列表
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userName = (String) principals.fromRealm(getName()).iterator()
				.next();
		User user = this.getUser(userName, "", "");
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			// info.addStringPermissions(group.getPermissionList());
			return info;
		} else {
			return null;
		}
	}

	/**
	 * 
	 * @param user
	 * @param password
	 * @param orgi
	 * @return
	 */
	@SuppressWarnings("unchecked")
	protected User getUser(String user, String password, String orgi) {
		User loginUser = new R3InnerUserAuthzImpl().getUser(user, orgi) ;
		return loginUser != null && loginUser.getPassword().equals(RivuTools.md5(password)) ? loginUser : null;
	}

}
